<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Utils\Cache;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class SendCodeMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var \Hyperf\HttpServer\Contract\ResponseInterface
     */
    protected $response;

    public function __construct(ContainerInterface $container, RequestInterface $request, \Hyperf\HttpServer\Contract\ResponseInterface $response)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $account = $this->request->input('account', '');
        $cache = Cache::getInstance();
        $cacheKey = 'code_' . $account;
        if (! empty($account)) {
            if (! is_null($cache->get($cacheKey))) {
                return $this->response->json([
                    'code' => ErrorCode::BUSY_ERROE,
                    'msg' => ErrorCode::getMessage(ErrorCode::BUSY_ERROE),
                ]);
            }
        }
        $result = $handler->handle($request);
        $content = $result->getBody()->getContents();
        $content = json_decode($content, true);
        if ($content['code'] == ErrorCode::SUCCESS) {
            $cache->set($cacheKey, '1', 60);
        }
        return $result;
    }
}
